import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:azlistview/azlistview.dart';
import 'package:flutter/services.dart';
import 'package:lpinyin/lpinyin.dart';

class ContactsFrame extends StatefulWidget {
  const ContactsFrame({Key? key}) : super(key: key);

  @override
  State<ContactsFrame> createState() => _ContactsFrameState();
}

class _ContactsFrameState extends State<ContactsFrame> {
  List<ContactInfo> _contacts = [];
  double susItemHeight = 40;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  void loadData() async {
    //加载联系人列表
    rootBundle.loadString('asset/data/contacts.json').then((value) {
      List list = json.decode(value);
      list.forEach((v) {
        _contacts.add(ContactInfo.fromJson(v));
      });
      _handleList(_contacts);
    });
  }

  void _handleList(List<ContactInfo> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(_contacts);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(_contacts);

    // add header.
    _contacts.insert(0, ContactInfo(name: 'header', tagIndex: '#', avatar: ''));

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(35.0),
        child: AppBar(
          elevation: 0,
          backgroundColor: Colors.grey.shade100,
          title: Text("通讯录", style: TextStyle(color: Colors.black)),
        ),
      ),
      body: AzListView(
        data: _contacts,
        itemCount: _contacts.length,
        susItemBuilder: (BuildContext context, int index) {
          if (_contacts[index].tagIndex == "#") {
            return const SizedBox.shrink();
          }
          return Container(
              margin: EdgeInsets.only(bottom: 10),
              color: Colors.white,
              width: MediaQuery.of(context).size.width,
              padding: const EdgeInsets.only(left: 13),
              child: Text(_contacts[index].tagIndex!,
                  style: TextStyle(color: Colors.grey.shade500, fontSize: 16)));
        },
        itemBuilder: (BuildContext context, int index) {
          if (index == 0) return _buildHeader();
          ContactInfo model = _contacts[index];
          return Container(
            margin: EdgeInsets.only(bottom: 10),
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Container(
                    width: 45,
                    height: 45,
                    color: Color(0xFFEDA459),
                    child: Icon(
                      Icons.account_circle,
                      color: Colors.white,
                      size: 30,
                    ),
                  ),
                ),
                Expanded(
                    child: Container(
                  height: 48,
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 10),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(color: Colors.grey.shade100))),
                  child: Text(model.name,
                      style: TextStyle(color: Colors.black, fontSize: 18)),
                ))
              ],
            ),
          );
        },
        physics: BouncingScrollPhysics(),
        indexBarData: SuspensionUtil.getTagIndexList(_contacts),
        indexBarMargin: EdgeInsets.all(10),
      ),
    );
  }

  Decoration getIndexBarDecoration(Color color) {
    return BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(20.0),
        border: Border.all(color: Colors.grey[300]!, width: .5));
  }

  Widget _buildHeader() {
    return Column(
      children: [
        Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
            width: MediaQuery.of(context).size.width,
            height: 46,
            color: Colors.grey.shade100,
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(6)),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset("asset/main/search.png", width: 20, height: 20),
                  SizedBox(width: 6),
                  Text(
                    "搜索",
                    style: TextStyle(
                      color: Color(0xFFbfbfbf),
                      fontSize: 16,
                    ),
                  )
                ],
              ),
            )),
        Container(
          margin: EdgeInsets.only(top: 10),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 45,
                  height: 45,
                  color: Color(0xFFEDA459),
                  child: Icon(
                    Icons.account_circle,
                    color: Colors.white,
                    size: 30,
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                height: 48,
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 10),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(color: Colors.grey.shade100))),
                child: Text("新的朋友",
                    style: TextStyle(color: Colors.black, fontSize: 18)),
              ))
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 10),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 45,
                  height: 45,
                  color: Color(0xFFEDA459),
                  child: Icon(
                    Icons.supervised_user_circle_rounded,
                    color: Colors.white,
                    size: 30,
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                height: 48,
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 10),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(color: Colors.grey.shade100))),
                child: Text("仅聊天的朋友",
                    style: TextStyle(color: Colors.black, fontSize: 18)),
              ))
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 10),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 45,
                  height: 45,
                  color: Color(0xFF61C072),
                  child: Icon(
                    Icons.people,
                    color: Colors.white,
                    size: 30,
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                height: 48,
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 10),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(color: Colors.grey.shade100))),
                child: Text("群组",
                    style: TextStyle(color: Colors.black, fontSize: 18)),
              ))
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 10, bottom: 10),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 45,
                  height: 45,
                  color: Color(0xFF4589E6),
                  child: Icon(
                    Icons.accessibility,
                    color: Colors.white,
                    size: 30,
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                height: 48,
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 10),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(color: Colors.grey.shade100))),
                child: Text("公众号",
                    style: TextStyle(color: Colors.black, fontSize: 18)),
              ))
            ],
          ),
        )
      ],
    );
  }
}

class ContactInfo extends ISuspensionBean {
  String name;
  String? tagIndex;
  String? namePinyin;
  String? avatar;

  Color? bgColor;
  IconData? iconData;

  String? img;
  String? id;
  String? firstletter;

  ContactInfo({
    required this.name,
    required this.avatar,
    this.tagIndex,
    this.namePinyin,
    this.bgColor,
    this.iconData,
    this.img,
    this.id,
    this.firstletter,
  });

  ContactInfo.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        img = json['img'],
        avatar = json['avatar'],
        id = json['id']?.toString(),
        firstletter = json['firstletter'];

  Map<String, dynamic> toJson() => {
//        'id': id,
        'name': name,
        'avatar': avatar,
        'img': img,
//        'firstletter': firstletter,
//        'tagIndex': tagIndex,
//        'namePinyin': namePinyin,
//        'isShowSuspension': isShowSuspension
      };

  @override
  String getSuspensionTag() => tagIndex!;

  @override
  String toString() => json.encode(this);
}
